public class BinarySearchTree {
   static class TreeNode{
        int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;

    /**
     * 插入数据
     * 时间复杂度O（logN）-O（N）
     * @param val
     */
   public void insert(int val){

       TreeNode node=new TreeNode(val);
       if(root==null){
           root=node;return;
       }
       TreeNode cur=root;
       TreeNode parent=null;
       while(cur!=null){
           if(cur.val<val){
               parent=cur;
               cur=cur.right;
           }else if(cur.val==val){
               return;
           }else{
               parent=cur;
               cur=cur.left;
           }
       }
       if(parent.val<val){
           parent.right=node;
       }else{
           parent.left=node;
       }
   }

    /**
     *搜索数据
     * @param val
     * @return
     */
    public  boolean search(int val){
        TreeNode cur= root;
        while(cur!=null){
            if(cur.val==val){
                return true;
            }else if(cur.val<val){
                cur=cur.right;
            }else{
                cur=cur.left;
            }
        }
        return false;
    }

    /**
     * 删除key节点
     * @param key
     */
    public void remove(int key){
        //先找有无这个节点
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val<key){
                parent=cur;
                cur=cur.right;
            }else if(key<cur.val){
                parent=cur;
                cur=cur.left;
            }else{
                removeNode(parent,cur);
                return;
            }
        }
    }
    private void removeNode(TreeNode parent,TreeNode cur){
        //左子不为空
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            }
            if(parent.left==cur){
                parent.left=cur.right;
            }else{
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            }
            if(parent.left==cur){
                parent.left=cur.left;
            }else{
                parent.right=cur.left;
            }
            //左右子树都不为空
            //找右子树的最小值替换
        }else {
            TreeNode target=cur.right;
            TreeNode tarPar=cur;
            while(target.left!=null){
                tarPar=target;
                target=target.left;
            }
            cur.val=target.val;
            //相当于左子树为空，删除该节点
            if(tarPar.right==target){
                tarPar.right=target.right;
            }else {
                tarPar.left = target.right;
            }
        }
    }

}
